<?php

namespace App\Http\Controllers\API\Admin;

use App\Http\Controllers\Controller;
use App\Miya\Models\Area;
use App\Miya\Models\Keyword;
use App\Miya\Models\Module;
use App\Miya\Models\SearchRecord;
use App\Miya\Models\UserView;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class HomeController extends Controller
{
    /**
     * 返回衍生关键词分布
     * @return \Illuminate\Http\JsonResponse
     */
    public function DerivateKeywords()
    {
        $data = Keyword::withCount(['derivatives'])->get()->map(function ($keyword) {
            return ['name' => $keyword->keyword, 'value' => $keyword->derivatives_count];
        });

        return response()->json($data);
    }

    /**
     * 返回地区关键词分布
     * @return \Illuminate\Http\JsonResponse
     */
    public function AreaKeywords()
    {
        $selected = [];
        $index = 0;
        $data = Area::withCount(['derivatives'])->orderBy('id')
            ->get()->map(function ($area) use (&$index, &$selected) {
                $selected[$area->name] = $index <= 20;
                $index++;
                return ['name' => $area->name, 'value' => $area->derivatives_count];
            });

        return response()->json(['data' => $data, 'selected' => $selected]);
    }

    /**
     * 返回关键词信息分布
     * @return \Illuminate\Http\JsonResponse
     */
    public function KeywordInfos()
    {
        $data = Keyword::withCount(['infos'])->get()->map(function ($keyword) {
            return ['name' => $keyword->keyword, 'value' => $keyword->infos_count];
        });

        return response()->json($data);
    }


    /**
     * 返回模块信息分布
     * @return \Illuminate\Http\JsonResponse
     */
    public function ModuleInfos()
    {
        $data = Module::withCount(['infos'])->get()->map(function ($module) {
            return ['name' => $module->name, 'value' => $module->infos_count];
        });

        return response()->json($data);
    }

    public function UserViews()
    {
        $cacheKey = 'echart_user_views';
        $data = Cache::remember($cacheKey, 60 * 60, function () {
            $data = [];
            $count = UserView::count();
            if ($count <= 0) {
                return [
                    'time' => [now()->format('Y-m-d')],
                    'start' => now()->format('Y-m-d'),
                    'data' => [0]
                ];
            }
            $startRecord = UserView::first();
            $days = [];
            for (
                $day = Carbon::parse($startRecord->time)->format('Y-m-d');
                $day <= now()->format('Y-m-d');
                $day = Carbon::parse($day)->addDay()->format('Y-m-d')
            ) {
                if ($day >= config('miya.cheat_page_views_from_day')) {
                    $days[$day] = config('miya.cheat_page_views');
                } else {
                    $days[$day] = 0;
                }
            }
            $data['time'] = array_keys($days);
            $data['start'] = now()->format('Y-01-01');

            UserView::select('time')->get()->each(function ($record) use (&$days) {
                $days[Carbon::parse($record->time)->format('Y-m-d')]++;
            });

            $data['data'] = array_values($days);

            return $data;
        });

        return response()->json($data);
    }

    public function IpSort()
    {
        $cacheKey = 'echart_ip_sort';
        $data = Cache::remember($cacheKey, 60 * 60, function () {
            $ips = UserView::select(['ip', DB::raw('count(*) as num')])
                ->where('time', '>=', now()->addMonths(-1))
                ->groupBy('ip')
                ->orderBy('num', 'DESC')
                ->take(config('miya.ip_sort_num'))
                ->pluck('num', 'ip')->toArray();

            $data = [
                'list' => count($ips) ? array_keys($ips) : ['127.0.0.1'],
                'values' => count($ips) ? array_values($ips) : [0]
            ];
            return $data;
        });

        return response()->json(['data' => $data]);
    }

    public function IpSortLocation()
    {
        $key = config('miya.ip_sort_location_token');

        $client = new Client();
        $params = [
            "ip" => request()->input('ip'),//需要查询的IP地址或域名
            "key" => $key,//应用APPKEY(应用详细页查询)
        ];
        try {
            $response = $client->post('http://apis.juhe.cn/ip/ipNew', ['form_params' => $params]);
            $json = $response->getBody()->getContents();
            $data = json_decode($json, true);

            return response()->json(['address' => $data]);
        } catch (\Exception $exception) {
            return response()->json(['address' => null]);
        }
    }

    public function SearchWords()
    {
        $records = SearchRecord::orderBy('count', 'DESC')
            ->take(config('miya.search_words_limit'))->get()->map(function ($word) {
                return [
                    "name" => $word->search,
                    "value" => $word->count
                ];
            });

        return response()->json($records);
    }
}
